package my.jwds.p606;

import my.jwds.p94.TreeNode;

public class Tree2str {
    public static void main(String[] args) {
        Tree2str obj = new Tree2str();

        TreeNode treeNode = TreeNode.to_binaryHaveNull(new Integer[]{1,2,3,null,4});
        System.out.println(obj.tree2str(treeNode));
    }



    public String tree2str(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        dfs(sb,root,false);
        return sb.toString();
    }


    void dfs(StringBuilder sb,TreeNode root,boolean flag){

        if (flag) sb.append("(");
        if (root != null){
            sb.append(root.val);
            dfs(sb,root.left,root.left != null || root.right != null);
            dfs(sb,root.right,root.right!= null);
        }
        if (flag) sb.append(")");
    }
}